package com.lyl.syt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.syt.client.HospFeignClient;
import com.lyl.syt.client.PatientFeignClient;
import com.lyl.syt.common.exception.YyghException;
import com.lyl.syt.common.result.ResultCodeEnum;
import com.lyl.syt.common.utils.HttpRequestHelper;
import com.lyl.syt.dao.OrderDao;
import com.lyl.syt.enums.OrderStatusEnum;
import com.lyl.syt.model.order.OrderInfo;
import com.lyl.syt.model.user.Patient;
import com.lyl.syt.rabbit.constant.MqConstant;
import com.lyl.syt.rabbit.service.RabbitService;
import com.lyl.syt.service.OrderService;
import com.lyl.syt.service.WeixinPayService;
import com.lyl.syt.vo.hosp.ScheduleOrderVo;
import com.lyl.syt.vo.msm.MsmVo;
import com.lyl.syt.vo.order.*;
import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderInfo> implements OrderService {
    private final PatientFeignClient patientFeignClient;
    private final HospFeignClient hospFeignClient;
    private final RabbitService rabbitService;
    private final OrderDao orderDao;
    @Lazy
    @Resource
    private WeixinPayService weixinPayService;

    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //获取订单中就诊人信息
        Patient patient = patientFeignClient.getPatientOrder(patientId);

        //获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospFeignClient.getScheduleOrderVo(scheduleId);

        //判断当前时间是否可以预约
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow() ||
                new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }

        //获取签名信息
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());

        //将数据添加到订单表中
        OrderInfo orderInfo = new OrderInfo();
        BeanUtil.copyProperties(scheduleOrderVo, orderInfo);
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        this.save(orderInfo);

        //调用医院接口，实现预约下单操作
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());         //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        //调用医院系统接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");

        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //todo 发送mq信息更新号源和短信通知
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("SMS_194640721");
            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);

            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConstant.ORDER_EXCHANGE, MqConstant.ORDER_ROUTING, orderMqVo);
        } else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo queryVo) {
        //orderQueryVo获取条件值
        String name = queryVo.getKeyword(); //医院名称
        Long patientId = queryVo.getPatientId(); //就诊人名称
        String orderStatus = queryVo.getOrderStatus(); //订单状态
        String reserveDate = queryVo.getReserveDate();//安排时间
        String createTimeBegin = queryVo.getCreateTimeBegin();
        String createTimeEnd = queryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        Page<OrderInfo> page = lambdaQuery()
                .like(StrUtil.isNotBlank(name), OrderInfo::getHosname, name)
                .eq(ObjectUtil.isNotEmpty(patientId), OrderInfo::getPatientId, patientId)
                .eq(ObjectUtil.isNotEmpty(orderStatus), OrderInfo::getOrderStatus, orderStatus)
                .ge(ObjectUtil.isNotEmpty(reserveDate), OrderInfo::getReserveDate, reserveDate)
                .ge(ObjectUtil.isNotEmpty(createTimeBegin), OrderInfo::getCreateTime, createTimeBegin)
                .le(ObjectUtil.isNotEmpty(createTimeEnd), OrderInfo::getCreateTime, createTimeEnd)
                .page(pageParam);

        page.getRecords().forEach(this::packOrderInfo);
        return page;
    }

    @Override
    public OrderInfo getOrder(String orderId) {
        return packOrderInfo(getById(orderId));
    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String, Object> map = new HashMap<>();
        OrderInfo orderInfo = this.packOrderInfo(this.getById(id));
        map.put("orderInfo", orderInfo);
        Patient patient
                = patientFeignClient.getPatientOrder(orderInfo.getPatientId());
        map.put("patient", patient);
        return map;
    }

    @Override
    public boolean cancelOrder(Long orderId) {
        //获取订单信息
        OrderInfo order = getById(orderId);
        //判断当前时间是否可以取消预约
        DateTime quitTime = new DateTime(order.getQuitTime());
        if (quitTime.isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        //调用三方接口，取消预约
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(order.getHoscode());
        if (null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", order.getHoscode());
        reqMap.put("hosRecordId", order.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);

        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updateCancelStatus");
        if (result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        } else {
            //是否支付 退款
            if (order.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
                //已支付 退款
                boolean isRefund = weixinPayService.refund(orderId);
                if (!isRefund) {
                    throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
            }
            //更改订单状态
            order.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(order);

            //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(order.getScheduleId());
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(order.getPatientPhone());
            msmVo.setTemplateCode("SMS_194640722");
            String reserveDate = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd") + (order.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", order.getHosname()+"|"+order.getDepname()+"|"+order.getTitle());
                put("reserveDate", reserveDate);
                put("name", order.getPatientName());
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConstant.ORDER_EXCHANGE, MqConstant.ORDER_ROUTING, orderMqVo);
        }
        return true;
    }

    @Override
    public void patientTips() {
        //查询今天需要看病的订单
        List<OrderInfo> orderList = lambdaQuery()
                .eq(OrderInfo::getReserveDate, DateUtil.today())
                .list();
        //发送短信提醒
        orderList.forEach(this::sendSeeADoctorMsm);
    }

    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo queryVo) {
        Map<String,Object> map = new HashMap<>();
        List<OrderCountVo> countVoList = orderDao.getOrderCount(queryVo);
        List<String> dateList = countVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        List<Integer> countList = countVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        map.put("dateList",dateList);
        map.put("countList",countList);
        return map;
    }

    private void sendSeeADoctorMsm(OrderInfo orderInfo) {
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
        Map<String,Object> param = new HashMap<String,Object>(){{
            put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
            put("reserveDate", reserveDate);
            put("name", orderInfo.getPatientName());
        }};
        msmVo.setParam(param);
        rabbitService.sendMessage(MqConstant.MSM_EXCHANGE, MqConstant.MSM_ROUTING, msmVo);
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

}
